<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="searchObj.data.role_name" size="medium" placeholder="日程名称" class="global-search-box"/>
      <el-button type="primary" size="medium" icon="el-icon-search" @click="getSchedules()">搜索</el-button>
      <el-button type="primary" size="medium" @click="reset()">重置</el-button>

      <span class="filter-container-right">
        <el-button v-permission= "{ permissionCode: 'schedule:add' }" type="primary" size="medium" icon="el-icon-plus" @click="addSchedule">新增</el-button>
        <el-button v-permission= "{ permissionCode: 'schedule:remove' }" type="danger" size="medium" icon="el-icon-close" @click="deleteSchedules">删除</el-button>
      </span>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      border
      highlight-current-row
      @selection-change="handleSelectChange">
      <el-table-column type="selection" width="40"/>
      <el-table-column align="center" label="日程名称" prop="title" min-width="150"/>
      <el-table-column align="center" label="发起人" prop="create_user" min-width="80"/>
      <el-table-column align="center" label="地址" prop="address" min-width="160"/>
      <el-table-column align="center" label="是否全天" min-width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.is_full_day === 0 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="描述" prop="description" min-width="150"/>
      <el-table-column align="center" label="开始时间" prop="start_date" min-width="160"/>
      <!--<el-table-column align="center" label="结束时间" prop="closed_date" min-width="160"/>
      <el-table-column align="center" label="创建日期" prop="create_date" min-width="160"/>
      <el-table-column align="center" label="修改日期" prop="modify_date" min-width="160"/>-->
      <el-table-column align="center" label="操作" min-width="270">
        <template slot-scope="scope">
          <el-button v-permission= "{ permissionCode: 'schedule:update' }" type="primary" size="mini" icon="el-icon-edit" @click="editSchedule(scope.row)">修改</el-button>
          <el-button v-permission= "{ permissionCode: 'schedule:remove' }" type="danger" size="mini" icon="el-icon-delete" @click="deleteSchedule(scope.row)">删除</el-button>
          <el-button v-permission= "{ permissionCode: 'schedule:addParticipator' }" type="success" size="mini" icon="el-icon-user" @click="participantChange(scope.row)">参与者</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title=" isEdit ? '编辑日程' : '新增日程'" :visible.sync="FormVisible" width="600px">
      <el-form ref="ruleForm" :model="scheduleForm" :rules="rules" >
        <el-form-item :label-width="formLabelWidth" label="日程名称" prop="title">
          <el-input v-model="scheduleForm.title" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="地址" prop="address">
          <el-input v-model.number="scheduleForm.address" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="开始时间" prop="start_date">
          <el-date-picker
            v-model="scheduleForm.start_date"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="开始日期时间"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="结束时间" >
          <el-date-picker
            v-model="scheduleForm.closed_date"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="结束日期时间"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="是否全天" prop="is_full_day">
          <el-select
            v-model="scheduleForm.is_full_day"
            reserve-keyword
            placeholder="是否全天">
            <el-option
              v-for="item in fullDayList"
              :key="item.value"
              :label="item.text"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="日程描述" prop="description">
          <el-input v-model="scheduleForm.description" type="textarea" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="参与者">
          <el-select
            v-model="scheduleForm.participators"
            :remote-method="getScheduleUsers"
            :loading="loading"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="参与者部门搜索">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.realName"
              :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd()">取 消</el-button>
        <el-button type="primary" @click="isEdit ? confirmEditSchedule('ruleForm') : confirmAddSchedule('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible" title="修改参与者" width="600px">
      <div style="margin-bottom: 20px">
        <el-tag v-for="item in participants" :key="item.id" closable type="primary" class="user-tag" @close="tagClose(item)">
          {{ item.realName }}
        </el-tag>
      </div>
      <el-select
        v-model="scheduleAddParticipant.participators"
        :remote-method="getScheduleUsers"
        :loading="loading"
        style="width:550px"
        multiple
        filterable
        remote
        reserve-keyword
        placeholder="参与者部门搜索">
        <el-option
          v-for="item in users"
          :key="item.id"
          :label="item.realName"
          :value="item.id"/>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="confirmParticipantChange()">确 定</el-button>
      </div>
    </el-dialog>
    <div class="global-paging">
      <el-pagination
        :page-size="10"
        :total="total"
        :page-sizes="[10, 20, 40]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
import commonApi from '@/api/commonApi'

export default {
  name: 'ScheduleList',
  data() {
    return {
      dialogFormVisible: false,
      loading: false,
      FormVisible: false,
      isEdit: false,
      list: null,
      users: null,
      listLoading: false,
      total: null,
      rules: {
        title: [
          { required: true, message: '请输入日程名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入日程地址', trigger: 'blur' }
        ],
        start_date: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        is_full_day: [
          { required: true, message: '请选择时间段', trigger: 'change' }
        ]
      },
      delScheduleIds: [],
      formLabelWidth: '120px',
      searchObj: {
        currentNo: 1,
        pageSize: 10,
        data: {
          beginTime: null,
          endTime: null,
          username: null
        }
      },
      searchUsers: {
        currentNo: 1,
        pageSize: 1000,
        data: {
          username: null,
          real_name: null,
          department: null
        }
      },
      scheduleForm: {},
      fullDayList: [
        { text: '全天', value: 0 },
        { text: '上午', value: 1 },
        { text: '下午', value: 2 }
      ],
      copyScheduleForm: {}, // 修改取消时使用
      scheduleAddParticipant: {
        schedule_id: null,
        participators: []
      },
      scheduleRemoveParticipant: {
        schedule_id: null,
        participators: []
      },
      participants: []
    }
  },
  created() {
    this.getSchedules()
  },
  methods: {
    tagClose(tag) {
      this.scheduleRemoveParticipant.participators.push(tag.id)
      this.participants = this.participants.filter(par => par !== tag)
    },
    participantChange(row) {
      this.dialogFormVisible = true
      this.scheduleAddParticipant.schedule_id = row.id
      this.scheduleRemoveParticipant.schedule_id = row.id
      commonApi(`/schedule/details/${row.id}`, 'get').then(response => {
        if (response.code === 1) {
          this.participants = response.data.users
        }
      })
    },
    confirmParticipantChange() {
      if (this.scheduleAddParticipant.participators.length > 0) {
        commonApi('/schedule/addParticipator', 'post', this.scheduleAddParticipant).then(response => {
          if (response.code === 1) {
            this.scheduleAddParticipant.participators = []
          }
        })
      }
      if (this.scheduleRemoveParticipant.participators.length > 0) {
        commonApi('/schedule/removeParticipator', 'post', this.scheduleRemoveParticipant).then(response => {
          if (response.code === 1) {
            this.scheduleRemoveParticipant.participators = []
          }
        })
      }
      this.dialogFormVisible = false
    },
    cancel() {
      this.dialogFormVisible = false
    },
    handleCurrentChange(val) {
      this.searchObj.currentNo = val
      this.getSchedules()
    },
    handleSizeChange(val) {
      this.searchObj.pageSize = val
      this.getSchedules()
    },
    getSchedules() {
      this.listLoading = true
      commonApi('/schedule/querySchedulePage', 'post', this.searchObj).then(response => {
        if (response.code === 1) {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    getScheduleUsers(dept) {
      this.searchUsers.data.department = dept
      commonApi('/schedule/users', 'post', this.searchUsers).then(response => {
        if (response.code === 1) {
          this.users = response.data.rows
        }
        this.loading = false
      })
    },
    reset() {
      for (const index in this.searchObj.data) {
        this.searchObj.data[index] = null
      }
      this.getSchedules()
    },
    handleSelectChange(valArr) {
      this.delScheduleIds = []
      for (let i = 0; i < valArr.length; i++) {
        this.delScheduleIds.push(valArr[i].id)
      }
    },
    addSchedule() {
      this.isEdit = false
      this.FormVisible = true
    },
    confirmAddSchedule(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          commonApi('/schedule/add', 'post', { schedule: this.scheduleForm }).then(response => {
            if (response.code === 1) {
              this.cancelAdd()
              this.listLoading = false
              this.getSchedules()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelAdd() {
      this.FormVisible = false
      if (!this.isEdit) {
        for (const index in this.scheduleForm) {
          if (index !== 'participators') {
            this.scheduleForm[index] = null
          } else {
            this.scheduleForm[index] = []
          }
        }
      } else {
        this.scheduleForm = this.copyScheduleForm
      }
    },
    deleteSchedule(row) {
      this.$confirm(`确定要删除日程：${row.title} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delScheduleIds.push(row.id)
        this.deleteSchedulesInterim()
      }).catch(() => {
      })
    },
    deleteSchedules() {
      if (this.delScheduleIds.length === 0) {
        this.$message({
          message: '请选择需要删除日程 ！',
          type: 'error'
        })
        return
      }
      this.$confirm(`确定要批量删除日程 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.deleteSchedulesInterim()
      }).catch(() => {
      })
    },
    deleteSchedulesInterim() {
      this.listLoading = true
      commonApi('/schedule/remove', 'post', this.delScheduleIds).then(response => {
        if (response.code === 1) {
          this.$message({
            message: '日程删除完成',
            type: 'success'
          })
          this.listLoading = false
          this.delScheduleIds = []
          this.getSchedules()
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    editSchedule(row = {}) {
      this.FormVisible = true
      this.isEdit = true
      this.scheduleForm = row
      this.copyScheduleForm = row
    },
    confirmEditSchedule(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          if (this.scheduleForm.closed_date === '') {
            delete this.scheduleForm.closed_date
          }
          commonApi('/schedule/update', 'post', this.scheduleForm).then(response => {
            if (response.code === 1) {
              this.cancelAdd()
              this.listLoading = false
              this.getSchedules()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss">
  .user-tag{
    margin: 0 10px 10px 0;
  }
</style>
